package com.why.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.why.dto.UserDTO;
import com.why.pojo.User;
import com.why.properties.JwtProperties;
import com.why.result.Result;
import com.why.service.UserService;
import com.why.utils.JwtUtil;
import com.why.utils.Md5Util;
import com.why.utils.ThreadLocalUtil;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user")
@Validated
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //注册
    @PostMapping("/register")
    public Result register(@Valid @RequestBody UserDTO userDTO) {
        log.info("***用户注册***");
        User user = userService.findByUserName(userDTO);
        if (user == null) {
            // 用户没被占用---注册
            userService.register(userDTO); // 确保传递User对象
            User byUserName = userService.findByUserName(userDTO);
            return Result.success(byUserName);
        }else
          // 占用，返回错误
          return Result.error("注册失败：用户已注册");
    }

    //登录
    @PostMapping("/login")
    public Result<String> login(@Valid @RequestBody UserDTO userDTO) {
        log.info("***用户登录***");
        //根据用户名查询User
        User user = userService.findByUserName(userDTO);
        //判断是否查询到
        if (user==null){
            throw new RuntimeException("用户未注册");
        }
        //密码比对: 对前端传过来的明文密码进行md5加密
        //判断密码是否正确
        if (!Md5Util.getMD5String(userDTO.getPassword()).equals(user.getPassword())){
            //密码错误
            throw new RuntimeException("密码错误");
        }

        //密码正确--为用户生成token
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",user.getId());
        claims.put("username",user.getUsername());
        String token = JwtUtil.genToken(claims);


        //把token存储到redis中
        //将生成的token作为键和值存入redis中，方便直接校验，过期时间和jwt一样 12个小时-1天
        stringRedisTemplate.opsForValue().set(token,token,12, TimeUnit.HOURS);

        return Result.success(token);
    }

    //获取用户详细信息
    @GetMapping("/userInfo")
    public Result<User> userInfo(){
        log.info("***获取用户详细信息***");
        //从token中获取username
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        UserDTO userDTO = new UserDTO();
        userDTO.setUsername(username);
        User user = userService.findByUserName(userDTO);
        System.out.println("获取用户详细信息："+user);
        return Result.success(user);
    }

    //修改用户信息
    @PutMapping("/update")
    public Result<User> update(@RequestBody @Validated User user){
        log.info("***修改用户信息***");
        userService.update(user);
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        User u = userService.findById(id);
        return Result.success(u);
    }

    //修改用户头像
    //@URL 校验参数是否是url地址形式
    @PatchMapping("/updateAvatar")
    public Result<String> updateAvatar(@RequestParam @URL String avatarUrl){
        log.info("***修改用户头像***");
        userService.updateAvatar(avatarUrl);
        return Result.success(avatarUrl);
    }

    //更新用户密码
    @PatchMapping("/updatePwd")
    public Result<String> updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
        log.info("***更新用户密码***");
        //手动参数校验:3个参数不能为空
        String oldPwd = params.get("old_pwd") ;
        String newPwd = params.get("new_pwd") ;
        String rePwd = params.get("re_pwd") ;
        if (!StringUtils.hasLength(oldPwd)||!StringUtils.hasLength(newPwd)
            ||!StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数");
        }

        //判断原密码是否正确
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        UserDTO userDTO = new UserDTO();
        userDTO.setUsername(username);
        User u = userService.findByUserName(userDTO);
        if (!u.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码错误");
        }

        //判断密码复写是否正确
        if (!rePwd.equals(newPwd)){
            return Result.error("两次密码填写不一致");
        }

        userService.updatePwd(newPwd);

        //修改成功后删除redis中原来的token
        stringRedisTemplate.opsForValue().getOperations().delete(token);

        return Result.success("修改密码成功！");
    }

}
